package vivace.view;

import java.awt.Container;
import java.awt.Dimension;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import vivace.helper.GUIHelper;
import vivace.model.App;
import vivace.model.Project;

public class HistoryFrame extends JFrame implements Observer {
	
	private static final long serialVersionUID = -6851396836953246375L;
	private Project model;
	private JList list;

	/**
	 * Constructor
	 * @param model
	 */
	public HistoryFrame(Project model) {
		this.model = model;
		App.addProjectObserver(this, App.Source.MODEL);
		Container c = getContentPane();
		list = new JList(model.getActionHistory());
		list.addListSelectionListener(new Controller());
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setSelectedIndex(model.currentStateIndex());
		list.setVisibleRowCount(-1);
		JScrollPane scrollPane = new JScrollPane(list);
		c.add(scrollPane);
		setTitle(lib.Texter.Text.getText("HISTORY"));
		setLocationRelativeTo(null);
		setIconImage(GUIHelper.icon);
		setPreferredSize(new Dimension(150, 300));
		setAlwaysOnTop(true);
		pack();
	}

	@Override
	public void update(Observable o, Object arg) {
		list.setListData(model.getActionHistory());
		list.setSelectedIndex(model.currentStateIndex());
	}
	
	private class Controller implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			if (!e.getValueIsAdjusting() && (list.getSelectedIndex() != -1)) {
				model.moveToState(list.getSelectedIndex());
			}
		}
		
	}
	
}
